package com.dmbjz.controller;

import com.dmbjz.entity.Comment;
import com.dmbjz.entity.CommentVo;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;


/** MongoTemplate 操作数据案例  */
@RestController
public class HelloController {


    @Autowired
    private MongoTemplate template;


    /*保存*/
    @RequestMapping("save")
    public void saveComment(){

        List<Comment> tempList = new ArrayList<>(3);
        tempList.add(new Comment("1","今天天气还行","dmbjz",new Date(),"游客A", LocalDateTime.now(),200,200,"1"));
        tempList.add(new Comment("2","手机今天欠费","dmbjz",new Date(),"游客B", LocalDateTime.now(),80,200,"1"));
        tempList.add(new Comment("3","你打算在今天干嘛","dmbjz",new Date(),"游客C", LocalDateTime.now(),170,200,"1"));
        tempList.add(new Comment("4","我觉得明晚不错","cctv",new Date(),"游客D", LocalDateTime.now(),100,200,"1"));
        tempList.add(new Comment("5","要学习知识","acfun",new Date(),"游客E", LocalDateTime.now(),100,200,"1"));
        template.insert(tempList,Comment.class); //批量保存


        Comment comment = new Comment("额外添加的数据","acfun",new Date(),"游客Z", LocalDateTime.now(),500,30,"1");
        template.save(comment);  //save只能保存单个数据

    }


    /*更新*/
    @RequestMapping("update")
    public void updateComment(){

        //批量更新
        Query query = new Query(Criteria.where("userid").is("dmbjz"));
        Update update = new Update().set("nickname","修改的名称")
                .set("replynum",678);
        UpdateResult updateResult = template.updateMulti(query, update, Comment.class);
        if(updateResult.getModifiedCount()>0){
            System.out.println("批量修改成功!");
        }

        //单个更新，更新最先查询到的数据
        Query query2 = new Query(Criteria.where("userid").is("acfun"));
        UpdateResult updateResult2 = template.upsert(query2, update, Comment.class);
        if(updateResult2.getModifiedCount()>0){
            System.out.println("单独修改成功!");
        }

    }


    /*删除*/
    @RequestMapping("del")
    public void deleteCommentById(){

        Query query = new Query(Criteria.where("id").nin("0"));
        template.remove(query,Comment.class);

    }


    /*查询*/
    @RequestMapping("find")
    public void findCommentList(Long page){

        //查询全部数据
        List<Comment> findList = template.findAll(Comment.class);
        findList.forEach(System.out::println);


        //根据ID查询
        Comment getId = template.findById("1", Comment.class);
        System.out.println("根据ID查询到的数据:"+getId);


        /*查询以 userid为dmbjz + likenum大于等于100 + content包含“还行”的数据*/
        System.out.println("------------开始条件查询------------");
        Query query = new Query(
                Criteria.where("userid").is("dmbjz")
                .and("likenum").gte(100)
        );
        //使用正则表达式进行匹配，Pattern.CASE_INSENSITIVE ：不区分大小写匹配
        Pattern pattern = Pattern.compile(".*还行.*", Pattern.CASE_INSENSITIVE);
        query.addCriteria(Criteria.where("contents").regex(pattern));
        List<Comment> comments = template.find(query, Comment.class);
        comments.forEach(System.out::println);


        //查询数据总量
        long count = template.count(new Query(), Comment.class);
        System.out.println("springboot集合中当前文档总数为: " + count);


        /*
         *  分页查询
         *      3 相当于 pageSize
         *      (page - 1) 相当于当前页码
         */
        System.out.println("------------开始分页查询------------");
        List<Comment> pageList = template.find(new Query().skip((page - 1) * 3).limit(3), Comment.class);
        pageList.forEach(System.out::println);


    }


    /*分组操作*/
    @RequestMapping("group")
    public void groupFind(){


        Criteria criteria = Criteria.where("likenum").gt(80);

        //根据工作日进行分组(聚合操作)
        Aggregation aggregation = Aggregation.newAggregation(

                Aggregation.match(criteria),                                      //查询条件，相当于MySQL中的 Where；这里为 likenum > 80
                Aggregation.group("userid")                                //Myngodb里数据的分组字段，这里为根据 userid 进行分组
                        .first("contents").as("contentsShow")       //获取group by 后的某个字段的首个值。AS 用于查询返回的别名，类似于MySQL中的 AS "xxxx"
                        .first("userid").as("userIdShow")           //获取grou by 后的userId字段的首个值，返回别名 "userIdShow"
                        .count().as("userCount")                            //获取分组后的数量
                        .sum("replynum").as("replyNumShow")        //统计 replynum 和，相当于 sum(replynum) AS "replynum"
                        .sum("likenum").as("likeNumShow"),         //统计 likenum 数，相当于 sum(likenum) AS "replynum"

                Aggregation.sort(Sort.Direction.ASC,"replyNumShow"),      //根据 replyNumShow 进行升序
                //Aggregation.skip(1),              //跳过数据,可用于分页起始数据
                Aggregation.limit(3)               //相当于 MySQL里的 Limit ,分页结束

        );

        //聚合查询，参数一：聚合条件，参数二：查询数据对应实体类，参数三：返回结果Class
        AggregationResults<CommentVo> listResult = template.aggregate(aggregation, Comment.class, CommentVo.class);
        //获取返回数据
        List<CommentVo> infoList = listResult.getMappedResults();
        infoList.forEach(System.out::println);

    }



}
